<template>
  <scroll-view scroll-y
               scroll-with-animation
               :scroll-into-view='scroll'>
    <view class="sidebar">
      <view v-for="(item,index) in category"
            :key="item.category_id"
            class="items"
            :class="{'active':index===currentIndex}"
            @click="onSidebarChange(index)"
            :id="'c'+index">
        {{item.category_name}}
      </view>
    </view>
  </scroll-view>
</template>

<script>
import eventBus from '@/common/eventbus'
export default {
  data() {
    return {
      currentIndex: 0, // sidebar 指针
      scroll: '', //滚动目标
    }
  },
  props: {
    category: Array,
  },
  methods: {
    onSidebarChange(index) {
      this.currentIndex = index
      // 指针变化 内容也变
      eventBus.$emit('scroll2view', index)
    },
  },
  mounted() {
    // 接收 指针变化
    eventBus.$on('scroll2sidebar', (index) => {
      this.currentIndex = index
      this.scroll = 'c' + index
    })
  },
}
</script>

<style lang="scss" scoped>
scroll-view {
  width: 200rpx;
  background-color: #f1f3f4;
}
.sidebar {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  .items {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    &.active {
      background-color: #fff;
    }
  }
}
</style>
